package com.wintop.springbootjwt.service.impl;

import com.wintop.springbootjwt.bean.User;
import com.wintop.springbootjwt.dao.SysUserDao;
import com.wintop.springbootjwt.service.UserService;
import com.wintop.springbootjwt.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    SysUserDao sysUserDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createWebToken(User user) {
        Instant now = Instant.now();
        String secretKey = JwtUtils.getSecretKey(now);
        String token = JwtUtils.create(secretKey, user.getId().toString(), now, 5);
        user.setLastLoginTime(LocalDateTime.ofInstant(now, ZoneId.systemDefault()));
        sysUserDao.updateByPrimaryKey(user);
        return token;
    }
}
